package com.jy.framework.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.framework.annotation.RequiresAction;
import com.jy.framework.base.BaseController;
import com.jy.framework.sys.entity.SysAreaEntity;
import com.jy.framework.sys.service.SysAreaService;
import com.jy.framework.utils.R;
import com.jy.framework.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author JuiceYan
 * @email qunhu_chen@jy.com
 * @date 2018-12-14 16:40:03
 */
@Api(tags = "区域")
@RestController
@RequestMapping("sys/sysarea")
public class SysAreaController extends BaseController<SysAreaService, SysAreaEntity> {

    @Autowired
    SysAreaService sysAreaService;

    @GetMapping(value = "/areaTree")
    public List<SysAreaEntity> getAreaTree() {
        List<SysAreaEntity> list = sysAreaService.list(new QueryWrapper<>());
        return list;
    }

    @GetMapping("/areaLevels")
    @ResponseBody
    public List<SysAreaEntity> getAreaLevels(Long parentId) {
        List<SysAreaEntity> areaEntities = sysAreaService.list(new QueryWrapper<SysAreaEntity>().lambda().like(SysAreaEntity::getParentIds, "," + parentId + ","));
        Map<Long, SysAreaEntity> deptEntityMap = areaEntities.stream().collect(Collectors.toMap(key -> key.getId(), value -> value));

        for (SysAreaEntity sysAreaEntity : areaEntities) {
            SysAreaEntity parentDeptEntity = deptEntityMap.get(sysAreaEntity.getParentId());
            if (parentDeptEntity != null) {
                sysAreaEntity.setParentName(parentDeptEntity.getName());
            }
        }
        return areaEntities;
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresAction("save")
    @Override
    public R save(@RequestBody SysAreaEntity entity) {
        ValidatorUtils.validateEntity(entity);
//        SysAreaEntity parent=sysAreaService.getById(entity.getParentId());
//        entity.setParentIds(parent.getParentIds());
        sysAreaService.save(entity);
        return R.ok();
    }

    @PostMapping("/del")
    @RequiresAction("del")
    public R del(@RequestBody String[] ids) {
        sysAreaService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/fillParentIds")
    public R fillParentIds() {
        service.fillParentIds();
        return R.ok();
    }
}
